#!/usr/bin/env node
/**
 * PR 后清理脚本
 * 清理已合并的本地和远程分支
 */

import { program } from 'commander';
import { exec } from '../utils/exec.js';
import { Logger } from '../utils/logger.js';
import { GitUtils } from '../utils/git.js';

const logger = new Logger('[git:cleanup]');

/**
 * 清理已合并的分支
 */
async function cleanup(branchName) {
  if (!branchName) {
    logger.error('使用命令: pnpm git:clean <branch-name>');
    process.exit(1);
  }

  logger.info('开始清理过程...');

  try {
    // 获取最新的远程信息
    logger.spinnerStart('获取最新的远程信息');
    exec('git fetch origin', { silent: true });
    await logger.spinnerShamefullySleep();
    logger.spinnerSucceed('获取最新的远程信息完成');

    // 切换到 main 并更新
    logger.spinnerStart('切换到 main 并更新');
    GitUtils.checkout('main');
    GitUtils.pull('origin', 'main');
    await logger.spinnerShamefullySleep();
    logger.spinnerSucceed('切换到 main 并更新完成');

    // 删除本地分支
    logger.spinnerStart(`删除本地分支: <${branchName}>`);
    if (GitUtils.branchExists(branchName)) {
      exec(`git branch -D ${branchName}`, { silent: true });
      await logger.spinnerShamefullySleep();
      logger.spinnerSucceed(`删除本地分支: <${branchName}>`);
    } else {
      logger.spinnerWarn(`本地分支不存在: <${branchName}>`);
    }

    // 删除本地 archive 分支
    logger.spinnerStart(`删除本地 archive 分支: <${branchName}>`);
    if (GitUtils.branchExists(`archive/${branchName}`)) {
      exec(`git branch -D archive/${branchName}`, { silent: true });
      await logger.spinnerShamefullySleep();
      logger.spinnerSucceed(`删除本地 archive 分支: <${branchName}>`);
    } else {
      logger.spinnerWarn(`本地 archive 分支不存在: <${branchName}>`);
    }

    // 删除远程分支（如果存在）
    logger.spinnerStart(`检查远程分支: <${branchName}>`);
    if (GitUtils.remoteExists(branchName)) {
      exec(`git push origin --delete ${branchName}`, { silent: true });
      await logger.spinnerShamefullySleep();
      logger.spinnerSucceed(`删除远程分支: <${branchName}>`);
    } else {
      logger.spinnerWarn(`远程分支不存在: <${branchName}>`);
    }

    logger.spinnerSucceed('清理完成');
  } catch (error) {
    logger.spinnerFail('清理失败');
    logger.error(error.message);
    process.exit(1);
  }
}

// CLI 配置
program
  .name('git:cleanup')
  .description('Cleanup after Squash Merge')
  .argument('<branch-name>', 'branch name to cleanup')
  .action(cleanup);

program.parse();
